import json
import os
import re
import string
import uuid
import random

from django.contrib.auth import login, logout
from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection

from ihome.utils.qiniu import qiniuimg
from users.models import User

# Create your views here.

import logging

from users.utils import LoginRequiredJSONMixin

logger = logging.getLogger('django')


class RegisterView(View):
    def post(self, request):
        data = json.loads(request.body.decode('utf-8'))
        mobile = data.get('mobile')
        phonecode = data.get('phonecode')
        password = data.get('password')
        # print(data)
        if not all([mobile, password, phonecode]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少重要参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 4103, 'errmsg': '手机号码错误'})
        if not re.match(r'^\d{6}$', phonecode):
            return JsonResponse({'errno': 4103, 'errmsg': '手机验证码错误'})
        if not re.match(r'^\w{4,20}$', password):
            return JsonResponse({'errno': 4103, 'errmsg': '密码格式错误'})
        conn = get_redis_connection('imgsmscode')
        sms_code = conn.get(f'sms_{mobile}')
        if not sms_code:
            return JsonResponse({'errno': 4103, 'errmsg': '您还未发送手机验证码'})

        sms_code = sms_code.decode('utf-8')
        if sms_code != phonecode:
            return JsonResponse({'errno': 4004, 'errmsg': '手机验证码错误'})
        try:
            username = ''.join(random.sample(string.ascii_letters + string.digits, 16))
            user = User.objects.create_user(username=username, mobile=mobile, password=password)
        except Exception:
            logger.error('创建用户失败')

            return JsonResponse({'errno': 4501, 'errmsg': '创建用户失败'})
        login(request, user)
        response = JsonResponse({'errno': 0, "errmsg": "注册成功"})
        response.set_cookie('username', user.username, 3600 * 24 * 14)
        return response


class LoginView(View):
    def get(self, request):
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'code': 4101, 'errmsg': '用户未登录'})
        return JsonResponse({"errno": "0", "errmsg": "已登录", "data": {"name": user.username, 'user_id': user.id}})

    def post(self, request):
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get("mobile")
        password = data_dict.get('password')
        if not all([mobile, password]):
            return JsonResponse({'errno': 4103, 'errmsg': '登录失败'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 4103, 'errmsg': '手机号码错误'})
        if not re.match(r'^\w{4,20}$', password):
            return JsonResponse({'errno': 4106, 'errmsg': '密码格式错误'})
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            logger.info('查找不到用户')
            return JsonResponse({'errno': 4001, 'errmsg': '查找不到用户'})
        if not user.check_password(password):
            return JsonResponse({'errno': 4106, 'errmsg': '密码错误'})
        login(request, user)
        user = request.user
        response = JsonResponse({'errno': '0', 'errmsg': 'ok'})
        response.set_cookie('username', user.username)

        return response

    def delete(self, request):
        if request.user.is_authenticated:
            logout(request)
            response = JsonResponse({'errno': 0, 'errmsg': '已经登出'})

            response.delete_cookie('username')
            return response
        return JsonResponse({'errno': 4101, 'errmsg': '用户未登录'})


class UserInfoView(LoginRequiredJSONMixin, View):
    def get(self, request):
        user = request.user
        try:
            avatar_url = user.avatar.url
        except Exception:
            avatar_url = ''

        data = {
            # 'avatar_url': '',
            'avatar_url': avatar_url,
            'create_time': user.date_joined,
            'mobile': user.mobile,
            'name': user.username,
            'user_id': user.id
        }

        return JsonResponse({
            'data': data,
            'errmsg': 'ok',
            'errno': '0'
        })


class AvatarView(LoginRequiredJSONMixin, View):
    def post(self, request):

        img_file = request.FILES.get("avatar")
        if not img_file:
            return JsonResponse({'errno': 4103, 'errmsg': '缺少重要参数'})
        file_content = img_file.read()
        file_name = str(uuid.uuid4())
        file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'image/{file_name}.jpg')
        with open(file_path, 'wb') as f:
            f.write(file_content)
        # print(file_name)

        ret_hash = qiniuimg(file_name, file_path)
        print(ret_hash)
        try:
            user = User.objects.get(pk=request.user.id)
        except User.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({'errno': 4011, 'errmsg': '	数据库查询错误'})
        try:
            user.avatar = ret_hash
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4011, 'errmsg': '	数据库修改错误'})
        user = User.objects.get(pk=request.user.id)
        avatar_url = user.avatar.url
        # print(avatar_url)
        if os.path.exists(file_path):
            os.remove(file_path)
        else:
            return JsonResponse({'errno': 4011, 'errmsg': '	数据库修改错误'})
        return JsonResponse({'data':{'avatar_url':avatar_url}, 'errno': 0, 'errmsg': "头像上传成功"})


class UpdateNameView(LoginRequiredJSONMixin, View):
    def put(self, request):
        name = json.loads(request.body.decode('utf-8')).get('name')
        if not name:
            return JsonResponse({'errno': 4103, 'errmsg': '缺少重要参数'})
        user = request.user
        try:
            user = User.objects.get(pk=user.id)
            user.username = name
            user.save()
        except User.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({'errno': 4011, 'errmsg': '	数据库查询错误'})
        return JsonResponse({"errno": 0, "errmsg": "修改成功"})


class AuthNameView(LoginRequiredJSONMixin, View):
    def post(self, request):
        data = json.loads(request.body.decode('utf-8'))
        real_name = data.get('real_name')
        id_card = data.get('id_card')
        if not all([real_name, id_card]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少重要参数'})
        if not re.match(r'^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',
                        id_card):
            return JsonResponse({'errno': 4004, 'errmsg': '身份证数据有误'})
        user = request.user
        try:
            user = User.objects.get(pk=user.id)
            user.real_name = real_name
            user.id_card = id_card
            user.save()
        except User.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({'errno': 4011, 'errmsg': '	数据库查询错误'})
        return JsonResponse({"errno": 0, "errmsg": "认证信息保存成功"})


    def get(self,request):
        user = request.user
        try:
            user = User.objects.get(pk=user.id)
        except User.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({
                'errno': 4001,
                'errmsg': '数据查询错误'
            })
        real_name = user.real_name
        id_card = user.id_card
        if not all([real_name,id_card]):
            return JsonResponse({
                'errno': 4002,
                'errmsg': '您还未实名认证，实名认证后才可以发布房源信息'
            })
        return JsonResponse({
            'errno': 0,
            'errmsg': 'ok',
            'data': {
                'real_name': real_name,
                'id_card': id_card
            }
        })
